<template>
  <div class="script-category-page">
    <header class="top-nav">
      <div class="search-bar">
        <span class="search-icon">🔍</span>
        <input type="text" placeholder="输入剧本名，快速找到哈" v-model="filters.name" @keyup.enter="applyFilters" />
      </div>
    </header>

    <section class="filter-tags">
      <div class="tag-row">
        <span
            class="tag"
            :class="{ active: activeCategory === '全部' }"
            @click="selectCategory('全部')"
        >全部</span>
        <span
            v-for="category in categories"
            :key="category"
            class="tag"
            :class="{ active: activeCategory === category }"
            @click="selectCategory(category)"
        >{{ category }}</span>
      </div>
      <div class="tag-row">
         <span
             v-for="count in [4, 5, 6, 7, 8, 9]"
             :key="count"
             class="tag"
             :class="{ active: filters.supportCount === count }"
             @click="selectSupportCount(count)"
         >{{ count }}人</span>
      </div>
      <div class="tag-row">
         <span
             v-for="tag in tags"
             :key="tag"
             class="tag"
             :class="{ active: filters.tagName === tag }"
             @click="selectTag(tag)"
         >{{ tag }}</span>
      </div>
    </section>

    <main class="scrollable-main">
      <section class="script-list">
        <div v-for="script in scripts" :key="script.id" class="script-card" @click="goToDetail(script.id)">
          <div v-if="script.isTop === 1" class="pinned-tag">置顶</div>
          <img :src="script.coverImage" alt="剧本封面" class="cover-image" />
          <div class="script-info">
            <h3>{{ script.name }}</h3>
            <p class="meta">{{ formatSupportCount(script.supportCount) }} {{ script.duration }}h</p>
            <p class="difficulty">{{ script.level }}</p>
            <div class="tags">
              <span v-for="tag in script.tagName" :key="tag" class="tag">{{ tag }}</span>
            </div>
            <p class="price">{{ script.pricePerUser }}元 / 位</p>
          </div>
        </div>
      </section>
      <div v-if="isLoading && hasMore" class="loading-indicator">
        <span class="spinner"></span>
        <span>加载中...</span>
      </div>
      <div v-if="!hasMore && scripts.length > 0" class="no-more">没有更多剧本了</div>
    </main>
  </div>
</template>

<script>
import { getCategoriesNamesService, getScriptTagNamesService, getScriptsByFilterService } from '@/api/user.js';

export default {
  name: 'ScriptCategory',
  data() {
    return {
      categories: [],
      tags: [],
      scripts: [],
      totalScripts: 0,
      activeCategory: '全部',
      filters: {
        name: '',
        supportCount: '',
        tagName: '',
        categoryName: '',
        pageNo: 1,
        pageSize: 5,
      },
      hasMore: true,
      isLoading: false,
      scrollTop: 0,
      inited: false,
      cacheKey: 'scriptCategoryCache',
    };
  },
  methods: {
    async fetchFilters() {
      try {
        const categoriesRes = await getCategoriesNamesService();
        this.categories = categoriesRes.data;

        const tagsRes = await getScriptTagNamesService();
        this.tags = tagsRes.data;
      } catch (error) {
        console.error("Failed to fetch filters:", error);
      }
    },
    async fetchScripts(isLoadMore = false) {
      if (this.isLoading) return;
      this.isLoading = true;
      try {
        this.filters.pageSize = 5;
        const params = { ...this.filters };
        params.categoryName = this.activeCategory === '全部' ? '' : this.activeCategory;
        const res = await getScriptsByFilterService(params);
        if (isLoadMore) {
          this.scripts = this.scripts.concat(res.data.results);
        } else {
          this.scripts = res.data.results;
        }
        this.totalScripts = res.data.total;
        this.hasMore = this.scripts.length < this.totalScripts;
      } catch (error) {
        console.error("Failed to fetch scripts:", error);
      } finally {
        this.isLoading = false;
      }
    },
    applyFilters() {
      this.filters.pageNo = 1;
      this.hasMore = true;
      this.scripts = [];
      this.fetchScripts().then(() => {
        this.filters.pageNo += 1;
        this.fetchScripts(true);
      });
    },
    selectCategory(category) {
      this.activeCategory = category;
      this.applyFilters();
    },
    selectSupportCount(count) {
      this.filters.supportCount = this.filters.supportCount === count ? '' : count;
      this.applyFilters();
    },
    selectTag(tag) {
      this.filters.tagName = this.filters.tagName === tag ? '' : tag;
      this.applyFilters();
    },
    formatSupportCount(counts) {
      if (!counts || counts.length === 0) return '';
      if (counts.length === 1) return `${counts[0]}人`;
      const min = Math.min(...counts);
      const max = Math.max(...counts);
      return `${min}-${max}人`;
    },
    goToDetail(scriptId) {
      // 记录滚动位置
      const main = this.$el.querySelector('.scrollable-main');
      if (main) {
        this.scrollTop = main.scrollTop;
        sessionStorage.setItem('categoryScrollTop', this.scrollTop);
      }
      this.$router.push({ name: 'ScriptDetail', params: { id: scriptId } });
    },
    handleScroll() {
      const main = this.$el.querySelector('.scrollable-main');
      if (!main || this.isLoading || !this.hasMore) return;
      const threshold = 100;
      if (main.scrollTop + main.clientHeight >= main.scrollHeight - threshold) {
        this.filters.pageNo += 1;
        this.fetchScripts(true);
      }
    }
  },
  mounted() {
    const cacheStr = sessionStorage.getItem(this.cacheKey);
    if (cacheStr) {
      const cache = JSON.parse(cacheStr);
      this.scripts = cache.scripts;
      this.totalScripts = cache.totalScripts;
      this.activeCategory = cache.activeCategory;
      this.filters = cache.filters;
      this.hasMore = cache.hasMore;
      this.categories = cache.categories;
      this.tags = cache.tags;
      this.$nextTick(() => {
        const main = this.$el.querySelector('.scrollable-main');
        if (main) main.scrollTop = cache.scrollTop || 0;
      });
      this.inited = true;
    } else {
      this.fetchFilters();
      this.fetchScripts().then(() => {
        this.filters.pageNo += 1;
        this.fetchScripts(true);
      });
      this.inited = true;
    }
    this.$nextTick(() => {
      const main = this.$el.querySelector('.scrollable-main');
      if (main) {
        main.addEventListener('scroll', this.handleScroll);
      }
    });
  },
  beforeRouteLeave(to, from, next) {
    const main = this.$el.querySelector('.scrollable-main');
    const cache = {
      scripts: this.scripts,
      totalScripts: this.totalScripts,
      activeCategory: this.activeCategory,
      filters: this.filters,
      hasMore: this.hasMore,
      scrollTop: main ? main.scrollTop : 0,
      categories: this.categories,
      tags: this.tags,
    };
    sessionStorage.setItem(this.cacheKey, JSON.stringify(cache));
    next();
  },
  beforeDestroy() {
    const main = this.$el.querySelector('.scrollable-main');
    if (main) {
      main.removeEventListener('scroll', this.handleScroll);
    }
  },
  activated() {
    // 恢复滚动位置
    this.$nextTick(() => {
      const main = this.$el.querySelector('.scrollable-main');
      const scrollTop = sessionStorage.getItem('categoryScrollTop');
      if (main && scrollTop) {
        main.scrollTop = Number(scrollTop);
      }
    });
  },
};
</script>

<style scoped>
/* Base styles */
.script-category-page {
  background-color: #f7f8fa;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

/* Top Navigation */
.top-nav {
  display: flex;
  align-items: center;
  padding: 6px 10px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 20;
  min-height: 38px;
}

.back-button {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  cursor: pointer;
  padding-right: 12px;
}

.search-bar {
  flex-grow: 1;
  display: flex;
  align-items: center;
  background-color: #f2f3f5;
  border-radius: 14px;
  padding: 4px 10px;
}

.search-bar .search-icon {
  margin-right: 8px;
  color: #969799;
}

.search-bar input {
  border: none;
  background: none;
  outline: none;
  width: 100%;
  font-size: 13px;
  color: #333;
}

.search-bar input::placeholder {
  color: #969799;
}

/* Filter Section */
.filter-tags {
  padding: 6px 10px;
  background-color: #fff;
  margin-top: 0;
  position: sticky;
  top: 38px;
  z-index: 15;
  box-shadow: 0 2px 4px rgba(0,0,0,0.03);
}

.tag-row {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 6px;
}
.tag-row:last-child {
  margin-bottom: 0;
}

.tag-row .tag {
  padding: 3px 9px;
  background-color: #f2f3f5;
  border-radius: 12px;
  font-size: 12px;
  cursor: pointer;
  color: #555;
  transition: all 0.2s ease-in-out;
  margin-right: 0;
  margin-bottom: 0;
}

.tag-row .tag.active {
  background-color: #007aff;
  color: #fff;
  font-weight: 500;
}

/* 让 main 区域可滚动 */
.scrollable-main {
  flex: 1 1 0%;
  overflow-y: auto;
  min-height: 0;
  /* 适配移动端，防止被顶部遮挡 */
  margin-top: 0;
}

/* Script List */
.script-list {
  padding: 16px;
}

.script-card {
  display: flex;
  background-color: #fff;
  border-radius: 12px;
  margin-bottom: 16px;
  padding: 16px;
  position: relative;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: transform 0.2s ease-in-out;
}
.script-card:hover {
  transform: translateY(-3px);
}

.pinned-tag {
  position: absolute;
  top: 12px;
  left: -2px;
  background-color: #fa3e3e;
  color: #fff;
  padding: 4px 10px;
  font-size: 12px;
  font-weight: 500;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
  box-shadow: 0 2px 4px rgba(250, 62, 62, 0.3);
}

.cover-image {
  width: 85px;
  height: 120px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 16px;
  flex-shrink: 0;
}

.script-info {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.script-info h3 {
  margin: 0 0 8px;
  font-size: 17px;
  font-weight: 600;
  color: #1c1c1e;
  line-height: 1.3;
}

.script-info .meta {
  font-size: 13px;
  color: #666;
  margin: 0 0 8px;
}

.script-info .difficulty {
  font-size: 12px;
  color: #ff9500;
  margin: 0 0 10px;
  border: 1px solid #ff9500;
  display: inline-block;
  padding: 2px 6px;
  border-radius: 4px;
  align-self: flex-start;
}

.script-info .tags {
  margin-bottom: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.script-info .tags .tag {
  background-color: #f2f3f5;
  font-size: 11px;
  padding: 3px 8px;
  border-radius: 4px;
  color: #888;
}

.script-info .price {
  font-size: 18px;
  color: #fa3e3e;
  font-weight: bold;
  margin-top: auto;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 18px 0 10px 0;
  color: #888;
  font-size: 15px;
  width: 100%;
}

.spinner {
  width: 22px;
  height: 22px;
  border: 3px solid #eee;
  border-top: 3px solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.no-more {
  text-align: center;
  color: #bbb;
  font-size: 14px;
  padding: 16px 0 10px 0;
}
</style> 